<template>
    <div class="allbox">
            <!-- 功能选择区 -->
            <div class="selection">
            <div @click="refresh(1)">
                <el-button type="info"><el-icon><RefreshRight /></el-icon></el-button>
            </div>
            <div @click="add()">
                <el-button type="success"><el-icon size="22" style="margin-right: 2px;"><Plus /></el-icon>添加</el-button>
            </div>
        </div>
        <!-- table -->
        <div class="table_box">
        <el-table  ref="ref_multipleTableRef" :data="tableData"  height="88vh"  @row-dblclick="db_Click"> <!--单击 和 双击 && 单选 和全选 -->
            <el-table-column type="selection" width="50" align="left" />
            <el-table-column label="序号" width="80" type="index" align="left" sortable=""/>
            <el-table-column prop="id" label="工号" width="140"/>
            <el-table-column prop="user" label="账号" width="120"/>
            <el-table-column prop="username" label="姓名" width="120" align="left"/>
            <el-table-column label="相片" width="180">
                
                <template #default="scope"> 
                    <el-image :src="setImage(scope.row.tx)" style="width: 100px; height: 100px" />   
                </template>

            </el-table-column>
            <el-table-column prop="password" label="密码" width="120"/>
            <el-table-column prop="sex" label="性别" width="80" align="left" />
            <el-table-column prop="phone" label="联系方式" width="120" align="center" />
            <el-table-column prop="position" label="部门" width="100" align="center" />
            <el-table-column prop="workDate" label="排班" width="140" align="center" />
            <el-table-column prop="workDay" label="工作日" min-width="140" align="center" />
            <el-table-column fixed="right" label="执行操作" width="180" align="center">
                <template #default="scope">
                   <div>
                        <el-button type="danger" style="width: 150px;"  @click.prevent="del(scope.$index)">
                            <el-icon size="20"><DeleteFilled /></el-icon>删除
                        </el-button>
                   </div>
                </template>
                </el-table-column>
        </el-table>
        </div>
          <!-- form表单 -->
          <el-dialog
            v-model="dialogVisible"
            title="编辑表单"
            draggable
            width="35%">
            <el-form :model="form" class="demo-ruleForm" v-loading="loading" size="large">

            <el-form-item required label="姓名" label-width="120px">
                <el-input v-model="form.username" type="text" autocomplete="off"  placeholder="请输入该用户的姓名"  />
            </el-form-item>

            <el-form-item required label="账号" label-width="120px" v-if="btn_text == '添加'">
                <el-input v-model="form.user" type="text" autocomplete="off"  placeholder="请输入该用户的账号"  />
            </el-form-item>

            <el-form-item required label="密码" label-width="120px">
                <el-input v-model="form.password" type="text" autocomplete="off" placeholder="请输入用户的密码" />
            </el-form-item>

            <el-form-item required label="联系方式" label-width="120px">
                <el-input v-model="form.phone" type="text" autocomplete="off" placeholder="请输入该用户的电话" />
            </el-form-item>

            <el-form-item required label="相片" label-width="120px" class="edit_line">
                <el-upload
                    v-model:fileList="fileList"
                    list-type="picture-card"
                    :drag="true"
                    :auto-upload="false"
                    :on-remove="handleRemove"
                    :on-change="onUpload">
                    <el-icon style="margin-top: 10px;color:darkturquoise;" size="40"><UploadFilled /></el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item required label="所属部门" label-width="120px">
                <el-select
                v-model="form.position"
                class="m-2"
                placeholder="请设置该用户的地区"
                size="large"
                style="width: 240px"
                >
                <el-option
                v-for="item in departmentList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
                />
                </el-select>
            </el-form-item>

            <el-form-item required label="排班时间" label-width="120px">
                <el-time-picker
                    v-model="form.workDate"
                    is-range arrow-control
                    format='HH:mm' value-format = 'HH:mm'
                    range-separator="至"
                    start-placeholder="选择该医生的排班时间"
                    end-placeholder="结束时间"
                    />
            </el-form-item> 

            <el-form-item required label="工作日" label-width="120px">
                <el-checkbox-group v-model="form.workDay" v-for="item in weekList" :key="item">
                    <el-checkbox :value="item" :label="item" style="margin-left: 35px;">
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>

            </el-form>
        <template #footer>
            <span class="dialog-footer">
            <el-button type="primary" @click="submit()" style="width: 80%;margin-right: 8%;height: 40px;">
                {{ btn_text }}
            </el-button>
            </span>
        </template>
        </el-dialog>

        <messageComp ref="ref_messageComp"></messageComp>
    </div>
  
</template>

<script setup>
import axios from "axios"
import { ref,getCurrentInstance } from "vue"
import { useStore } from "vuex";
import messageComp from "../components/messageComp.vue";
const ref_messageComp = ref(null) //弹窗message组件refs
const store = useStore()
const { ctx } = getCurrentInstance()
// 数据
let loading = ref(false) //加载
let dialogVisible = ref(false) //表单开关
let form = ref({
    workDate:[]
}) //表单数据 el-form
let tableData = ref([]) //表格数据-el-table
let btn_text = ref('添加')
let fileList = ref([]) //上传的图片
let departmentList = ref([]) //部门
let weekList = ref(['星期一','星期二','星期三','星期四','星期五','星期六','星期日'])



// 为了解决神秘的图片跨域问题
const setImage = (url) =>{
    if (url) {
        //帮我把url前面的http://127.0.0.1:8001转换成/api
        return url.replace("http://127.0.0.1:8001", "/api")
    }
}

// 提交
const submit = ()=>{
    if (btn_text.value == '添加') {
        addAPI()
    } else {
        updateAPI()
    }
   
}

const db_Click = (e)=>{
    dialogVisible.value = true
    btn_text.value = '修改'
    form.value = e
    fileList.value = []
    fileList.value.push({url:e.tx})
}

const updateAPI = () =>{
    // 01.先做好数据的格式
    let updateObject = Object.assign({}, form.value);//拷贝
    updateObject.workDate = form.value.workDate[0] + '-' + form.value.workDate[1]
    updateObject.workDay = form.value.workDay.join(",");
    updateObject.type = '医生'
    dialogVisible.value = false
    // 02.把数据都放进formData中
    console.log(fileList.value[0].raw);
    if (fileList.value[0].raw != 'undefined') {
        let formData =  new FormData
        formData.append('file',fileList.value[0].raw)
        formData.append('form',JSON.stringify(updateObject))
    }
    // 03.
    axios({
        method:'post',
        url:store.state.url + '/users/update',
        data:updateObject,
    }).then(res=>{
        if (res.data.code == 200) {
            ref_messageComp.value.messageSuccess('您更新了一条记录')
            refresh()
        }else{
            ref_messageComp.value.messageFail('更新失败')
        }
    }).catch(err=>{
        console.log(err);
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}
const addAPI = ()=>{
    if (fileList.value.length == 0) {
        ref_messageComp.value.messageFail('您尚未选择图片')
        return
    }
    // 01.先做好数据的格式
    let updateObject = Object.assign({}, form.value);//拷贝
    updateObject.workDate = form.value.workDate[0] + '-' + form.value.workDate[1]
    updateObject.workDay = form.value.workDay.join(",");
    updateObject.type = '医生'
    dialogVisible.value = false
    // 02.把数据都放进formData中
    let formData =  new FormData
    formData.append('file',fileList.value[0].raw)
    formData.append('form',JSON.stringify(updateObject))
    // 03.发射
    axios({
        method:'post',
        url:'/api/users/insert',
        data:formData,
    }).then(res=>{
        if (res.data.code == 200) {
            ref_messageComp.value.messageSuccess('您新增了一条记录')
            refresh()
        }else{
            ref_messageComp.value.messageFail('新增失败')
        }
    }).catch(err=>{
        console.log(err);
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}

// 获取用户列表
const getData = ()=>{
    axios({
        url:store.state.url + '/users'
    }).then(res=>{
        console.log(res);

        if (res.data.code == 200) {
            tableData.value = []
            let arr = res.data.data
            // 寻找类型为医生用户的数据
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].type == '医生') {
                    let obj = Object.assign({}, arr[i])
                    obj.workDate = arr[i].workDate.split('-')
                    obj.workDay = arr[i].workDay.split(',')
                    tableData.value.push(obj)
                }
            }
            // let arr = res.data.data.filter(item=>item.type == '医生') 
            // tableData.value = arr

        }
    }).catch(err=>{
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}


// 删除
const del = (index)=>{
    loading.value = true
    let timer = setInterval(() => {
            axios({
            method:'post',
            url: '/api/users/delete',
            data:{
                id:tableData.value[index].id
            },
        }).then(res=>{
            if (res.data.code == 200) {
                ref_messageComp.value.messageSuccess('您删除了一条记录')
                refresh()
            }else{
                ref_messageComp.value.messageFail('删除失败！')
            }
        }).catch(err=>{
            console.log(err);
            ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
        })
        loading.value = false
        clearInterval(timer)
    }, 1000);

}
// 获取部门数据
const getDepartment = ()=>{
    axios({
        url:store.state.url + '/class'
    }).then(res=>{
        if (res.data.code == 200) {
            departmentList.value = res.data.data
        }
    }).catch(err=>{
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}
// 刷新
const refresh = (n)=>{
    setTimeout(()=>{
        if (n) {
            ref_messageComp.value.messageSuccess('刷新成功')
        }
        getData()
        getDepartment()
    },300)
}
const handleRemove = (e,val)=>{ //删除编辑面板-上传图片
    console.log('删除图片',e);
    console.log('还剩余图片',val); 
    // 记住这个数组  这个是人家自带的
}
const onUpload = (e,val)=>{ //删除编辑面板-上传图片
    fileList.value = [] //清空数组否则累加图片了
    fileList.value.push(e)
    console.log('每上传一张图片',fileList.value);
}

const add = ()=>{
    fileList.value = []
    form.value = {}
    dialogVisible.value = true
    btn_text.value = '添加'

}
// 执行区
refresh()
</script>


<style scoped>
.selection{
    margin: 10px;
    width: 100%;
    height: 40px;
    line-height: 40px;
    /* border: 2px solid; */
    display: flex;

}
.selection>div{
    width: 70px;
    height: 100%;
    margin-left: 10px;
    border-radius: 5px;
}
/* 刷新 */
.selection>div:nth-child(1){
    margin-left: 40px;
}
.roles{
    width: 40%;
    margin: 5px;
    /* border: 2px solid ; */
}


</style>